package com.taiyuan.tongcheng.ui;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpConfig;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.CipherUtils;
import org.kymjs.kjframe.utils.StringUtils;
import org.kymjs.kjframe.utils.SystemTool;

import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import cn.jpush.android.api.JPushInterface;

import com.taiyuan.tongcheng.bean.UserInfo;
import com.taiyuan.tongcheng.db.TcDbHelper;
import com.taiyuan.tongcheng.http.HTTPFieldConstant;
import com.taiyuan.tongcheng.http.TcWebservice;
import com.taiyuan.tongcheng.http.WebData;
import com.taiyuan.tongcheng.jsonparser.TcJsParser;
import com.taiyuan.tongcheng.util.CommonUtil;
import com.taiyuan.tongcheng.util.SharePreferenceUtil;
import com.taiyuan.tongcheng.util.TcUtil;
import com.taiyuan.tongcheng.util.TimeCountUtil;
import com.tytc56.user.R;

/**
 * 
 * @Description 登录界面
 * @author wzq
 * @date 2015-7-23 下午7:13:38
 * @update (date)
 * @version V1.0
 */
public class CodeLoginActivity extends BaseActivity {
	// widget
	@BindView(id = R.id.etv_codelogin_phone)
	private EditText phoneEtv;
	@BindView(id = R.id.etv_codelogin_phonecode)
	private EditText codeEtv;
	@BindView(id = R.id.btn_login, click = true)
	private Button loginBtn;
	@BindView(id = R.id.btn_getLoginCode, click = true)
	private Button getSmsCode;


	@Override
	public void setRootView() {
		setContentView(R.layout.activity_codelogin);
	}

	@Override
	protected void initView() {
		super.initView();
	}

	/**
	 * 
	 * @Description: 初始化用户名密码
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-6-29 下午6:57:10
	 * @update (date)
	 */
	private void initEtv() {

		phoneEtv.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				if (!TcUtil.isMobileNO(phoneEtv.getText().toString())) {

					getSmsCode.setClickable(false);// 设置不能点击
					// 设置按钮为灰色，这时是不能点击的
					getSmsCode.setBackgroundResource(R.drawable.btn_disabled);
				} else {
					getSmsCode.setClickable(true);// 设置不能点击
					// 设置按钮为灰色，这时是不能点击的
					getSmsCode
							.setBackgroundResource(R.drawable.selector_btn_blue);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				
			}
		});
	}

	@Override
	public void initWidget() {
		super.initWidget();
		initView();
		getSmsCode.setClickable(false);// 设置不能点击
		// 设置按钮为灰色，这时是不能点击的
		getSmsCode.setBackgroundResource(R.drawable.btn_disabled);
		topTv.setText(R.string.code_login);
		rightTv.setVisibility(View.GONE);
		initEtv();
	}

	@Override
	public void widgetClick(View v) {
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.btn_login:
			codelogin();
			break;
		case R.id.btn_getLoginCode:
			
			if (SystemTool.checkNet(getApplicationContext())) {

				TimeCountUtil timeCountUtil = new TimeCountUtil(this, 60000,
						1000, getSmsCode);
				timeCountUtil.start();
				getSmsCode();

			}else{
				ViewInject.toast(getString(R.string.net_work_error));
			}
			
			break;

		default:
			break;
		}
	}

	/**
	 * 输入合法性检测
	 */
	private boolean inputCheck() {
		if (StringUtils.isEmpty(phoneEtv.getText().toString())) {
			showErroCustomToast(getString(R.string.account_not_empty));
			return false;
		}
		if (StringUtils.isEmpty(codeEtv.getText().toString())) {
			showErroCustomToast(getString(R.string.phonecode_not_empty));
			return false;
		}
		return true;
	}

	/**
	 * 
	 * @Description: 短信验证码登录
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-8-24 下午1:42:22
	 * @update (date)
	 */
	private void codelogin() {

		if (!inputCheck()) {
			return;
		}
		TcLoaddingDialog.show();
		long time = System.currentTimeMillis();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT,
				TcUtil.getApiName(TcWebservice.API.ACCOUNT_LOGIN_SMS));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE, phoneEtv
				.getText().toString());
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_SMS, codeEtv.getText()
				.toString());
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID,
				CommonUtil.getAndroidDeviceUnique(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER,
				SystemTool.getAppVersionCode(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_REGISTRATIONID,
				JPushInterface.getRegistrationID(getApplicationContext()));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM, time + "");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN, CipherUtils
				.md5(phoneEtv.getText().toString()
						+ codeEtv.getText().toString()
						+ "1"
						+ CommonUtil.getAndroidDeviceUnique(this)
						+ SystemTool.getAppVersionCode(this)
						+ JPushInterface
								.getRegistrationID(getApplicationContext())
						+ time + TcWebservice.signSecretKey));
		kjh.post(
				TcWebservice.WEBSERVER_IP + TcWebservice.API.ACCOUNT_LOGIN_SMS,
				params, new HttpCallBack() {
					@Override
					public void onSuccess(
							java.util.Map<String, String> headers, byte[] t) {
						if (t != null) {
							try {
								String str = URLDecoder.decode(new String(t),
										"UTF-8");
								WebData webData = TcJsParser.getWedataData(str);
								
								if (TcLoaddingDialog.isShowing()) {
									TcLoaddingDialog.cancel();
								}
								
								if (webData.getStatus() == 1) {
									ViewInject.toast(webData.getMsg());
									UserInfo info = TcJsParser.getUserInfo(webData
											.getData());
									TcDbHelper.saveUser(CodeLoginActivity.this, info);
									spUtil.setLoginFlag(1);
									GotoMain();
								} else {
									showErroCustomToast(webData.getMsg());
								}
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}

						}
					};
					

					@Override
					public void onFailure(int errorNo, String strMsg) {
						super.onFailure(errorNo, strMsg);
						if (errorNo == -1) {
							if (TcLoaddingDialog.isShowing()) {
								TcLoaddingDialog.cancel();
							}
							// 网络超时
							ViewInject.toast(strMsg);
						}
					}
					
				});

	}

	/**
	 * 
	 * @Description: 获取短信验证码
	 * @return void
	 * @throws
	 * @autour wzq
	 * @date 2015-8-24 下午3:42:13
	 * @update (date)
	 */
	private void getSmsCode() {

		long time = System.currentTimeMillis();
		HttpConfig config = new HttpConfig();
		config.cacheTime = 0;
		KJHttp kjh = new KJHttp(config);
		HttpParams params = new HttpParams();
		params.put(HTTPFieldConstant.POST_PARAMS_COMMON_ACT,
				TcUtil.getApiName(TcWebservice.API.ACCOUNT_GET_SMS_LOGIN));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_MOBILE, phoneEtv
				.getText().toString());
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_FROM, "1");
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_DEVID,
				CommonUtil.getAndroidDeviceUnique(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_VER,
				SystemTool.getAppVersionCode(this));
		params.put(HTTPFieldConstant.POST_PARAMS_ACCOUNT_TM, time + "");
		params.put(
				HTTPFieldConstant.POST_PARAMS_ACCOUNT_SIGN,
				(CipherUtils.md5(phoneEtv.getText().toString() + "1"
						+ CommonUtil.getAndroidDeviceUnique(this)
						+ SystemTool.getAppVersionCode(this) + time
						+ TcWebservice.signSecretKey)).toUpperCase());
		kjh.post(TcWebservice.WEBSERVER_IP
				+ TcWebservice.API.ACCOUNT_GET_SMS_LOGIN, params,
				new HttpCallBack() {
					@Override
					public void onSuccess(
							java.util.Map<String, String> headers, byte[] t) {
						if (t != null) {
							try {
								String str = URLDecoder.decode(new String(t),
										"UTF-8");
								WebData webData = TcJsParser.getWedataData(str);
								if (webData.getStatus() == 1) {
									ViewInject.toast(webData.getMsg());
									
								} else {
									ViewInject.toast(webData.getMsg());
								}

							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}
					};
				});
	}

}
